package com.example.test_witns;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.test_witns.databinding.ActivityViewSensorBinding;
import com.example.test_witns.pojo.TemperatureHumidityResponse;
import com.google.gson.Gson;

import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;

public class TempHumiActivity extends AppCompatActivity {
    private ActivityViewSensorBinding binding;
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable runnable;
    private static final long INTERVAL = 5000;
    private TextView textView_Temperature;
    private TextView textView_Humidity;
    private volatile boolean running = true;
    private double alertTempValue;
    private double alertHumiValue;

    public interface TemperatureHumidityResponseService{
        @GET("getLatestTemperatureHumidity")
        Call<TemperatureHumidityResponse> getLatestTemperatureHumidity();
    }

    public interface TemperatureHumidityCallback {
        void onSuccess(String temperatureStr, String humidityStr);
        void onFailure(String errorMessage);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityViewSensorBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        textView_Temperature = findViewById(R.id.temperature);
        textView_Humidity = findViewById(R.id.humidity);

        Window window = getWindow();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        window.setStatusBarColor(Color.parseColor("#dddddd"));
        Objects.requireNonNull(getSupportActionBar()).hide();

        View monitoringStart = findViewById(R.id.monitoringStart);
        monitoringStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startRunnable();
            }
        });

        View monitoringEnd = findViewById(R.id.monitoringEnd);
        monitoringEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopRunnable();
            }
        });

    }

    public void startRunnable(){
        runnable = new Runnable() {
            @Override
            public void run() {
                if (running){
                    getTemperatureHumidity(new TemperatureHumidityCallback() {
                        @Override
                        public void onSuccess(String temperature1, String humidity1) {
                            textView_Temperature.setText(temperature1);
                            textView_Humidity.setText(humidity1);
                            Toast.makeText(TempHumiActivity.this, "获取成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(String errorMessage) {

                        }
                    });
                    handler.postDelayed(this, INTERVAL);
                }
            }

        };

        handler.post(runnable);
    }

    private void stopRunnable() {
        running = false;
    }

    public void getTemperatureHumidity(TemperatureHumidityCallback callback) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://43.136.25.65:8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        TemperatureHumidityResponseService service = retrofit.create(TemperatureHumidityResponseService.class);
        Call<TemperatureHumidityResponse> call = service.getLatestTemperatureHumidity();
        call.enqueue(new Callback<TemperatureHumidityResponse>() {
            @Override
            public void onResponse(Call<TemperatureHumidityResponse> call, Response<TemperatureHumidityResponse> response) {
                if (response.isSuccessful()) {
                    TemperatureHumidityResponse TemperatureHumidityResponse = response.body();
                    if (TemperatureHumidityResponse != null) {
                        // 将double数据转换为字符串
                        String temperatureStr = String.valueOf(TemperatureHumidityResponse.getData().getTemperature());
                        String humidityStr = String.valueOf(TemperatureHumidityResponse.getData().getHumidity());
                        Log.d("RetrofitResponse", TemperatureHumidityResponse.toString());
                        try {
                            String json = new Gson().toJson(TemperatureHumidityResponse);
                            Log.d("RetrofitResponse", "JSON: " + json);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        // 使用转换后的字符串
                        callback.onSuccess(temperatureStr, humidityStr);
                        // 例如，更新UI或进行其他操作
                    } else {
                        callback.onFailure("返回的数据为空");
                    }
                } else {
                    callback.onFailure("获取失败，HTTP状态码: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<TemperatureHumidityResponse> call, Throwable t) {
                callback.onFailure("失败啦,请检查网络: " + t.getMessage());
            }
        });
    }

}
